package com.kevin.Code.Hash;

import java.util.HashMap;

/**
 * @author Vinlee Xiao
 * @Classname LongestSubstringWithoutRepeatingCharacters
 * @Description Leetcode 3. 无重复字符的最长子串 中等难度
 * @Date 2021/10/28 19:20
 * @Version 1.0
 */
public class LongestSubstringWithoutRepeatingCharacters {

    /**
     * @param s
     * @return
     */
    public int lengthOfLongestSubstring(String s) {

        int len = s.length();

        if (len == 0) {
            return 0;
        }

        if (len == 1) {
            return 1;
        }

        //用于存储字符所对应的下标+1
        HashMap<Character, Integer> hashMap = new HashMap<>();

//        int start = 0;
//        int end = 0;
        //记录最大无重复子串的长度
        int res = 0;
        for (int start = 0, end = 0; end < len; end++) {

            //
            char ch = s.charAt(end);

            if (hashMap.containsKey(ch)) {
                start = Math.max(hashMap.get(ch), start);
            }

            res = Math.max(res, end - start + 1);
            hashMap.put(ch, end + 1);


        }


        return res;
    }

    public static void main(String[] args) {
        LongestSubstringWithoutRepeatingCharacters longestSubstringWithoutRepeatingCharacters = new LongestSubstringWithoutRepeatingCharacters();
        int i = longestSubstringWithoutRepeatingCharacters.lengthOfLongestSubstring("pwwkew");
        System.out.println(i);
    }
}
